import { useBreakpoint } from 'antd'; // 引入useBreakpoint来检测屏幕尺寸

const DefaultLayout = () => {
  const { styles } = useStyle();
  const [content, setContent] = useState("");
  const [messages, setMessages] = useState([]);
  const [conversationsItems, setConversationsItems] = useState([]);
  const [activeKey, setActiveKey] = useState("init");
  const [loading, setLoading] = useState(false);
  const [historyMessages, setHistoryMessages] = useState([]);
  const [conversationId, setConversationId] = useState(null);
  const [selectedModel, setSelectedModel] = useState("qwen2.5-72b-instruct");
  const [collapsed, setCollapsed] = useState(false);

  const { xs, sm, md, lg, xl } = useBreakpoint(); // 获取屏幕尺寸信息

  const fetchData = useCallback(async () => {
    if (activeKey === "init" || activeKey === "AddConversation") {
      try {
        const conversations = await fetchApi('/conversations');
        const formattedConversations = conversations.data?.map(conversation => ({
          key: conversation.conversation_id,
          label: conversation.title,
        })) || [];
        setState(prevState => ({
          ...prevState,
          conversationsItems: formattedConversations,
          activeKey: formattedConversations.length > 0 && activeKey === "AddConversation" ? formattedConversations[0].key : activeKey,
          conversationId: formattedConversations.length > 0 && activeKey === "AddConversation" ? formattedConversations[0].key : conversationId,
        }));
        if (formattedConversations.length === 0) {
          setState(prevState => ({
            ...prevState,
            conversationsItems: [],
            activeKey: null,
            conversationId: null,
          }));
        }
      } catch (error) {
        console.error('Error fetching conversations:', error);
      }
    } else if (conversationId) {
      try {
        const conversationDetails = await fetchApi(`/conversations/${conversationId}`);
        const formattedMessages = conversationDetails.data?.map(msg => ({
          id: msg.message_id,
          message: <ContentRenderer content={msg.content} />,
          role: msg.sender_type,
        })) || [];
        setMessages(formattedMessages);
      } catch (error) {
        console.error('Error fetching conversation details:', error);
      }
    }
  }, [activeKey, conversationId, fetchApi]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);


  const requestChat = useCallback(async (question) => {
    const userMessage = {
      id: uuidv4(),
      message: question,
      role: "user",
    };

    const assistantMessage = {
      id: uuidv4(),
      message: <ContentRenderer content="等待中..." />,
      role: "assistant",
    };

    setMessages(prevMessages => [...prevMessages, userMessage, assistantMessage]);
    setState(prevState => ({
      ...prevState,
      historyMessages: [
        ...prevState.historyMessages,
        { id: userMessage.id, role: "user", content: question },
      ],
      loading: true,
    }));

    let newContent = '';
    try {
      fetchRequest.create(
        {
          message: question,
          history: historyMessages,
          stream: true,
          model: selectedModel,
          conversation_id: conversationId,
        },
        {
          onUpdate: (response) => {
            if (conversationId === null) {
              setState(prevState => ({
                ...prevState,
                activeKey: "AddConversation",
              }));
            }
            const data = JSON.parse(response.data);
            if (data?.data?.[0]?.choices?.[0]?.delta?.content) {
              newContent += data.data[0].choices[0].delta.content;
              updateMessages(assistantMessage.id, <ContentRenderer content={newContent} />);
              updateHistoryMessages(assistantMessage.id, newContent);
            }
          },
          onSuccess: () => {
            setState(prevState => ({
              ...prevState,
              loading: false,
            }));
          },
          onError: (e) => {
            console.error("请求有错误！", e);
            if (e.name !== 'AbortError') {
              handleApiError(e);
              updateMessages(assistantMessage.id, "忙碌中，请重试");
            }
            setState(prevState => ({
              ...prevState,
              loading: false,
            }));
          },
        }
      );
    } catch (error) {
      if (error.name !== 'AbortError') {
        console.error("请求有错误！", error);
        handleApiError(error);
        updateMessages(assistantMessage.id, "忙碌中，请重试");
      }
      setState(prevState => ({
        ...prevState,
        loading: false,
      }));
    }
  }, [conversationId, historyMessages, selectedModel, fetchRequest]);


  const onSubmit = useCallback((nextContent) => {
    if (!nextContent) return;
    requestChat(nextContent);
    setState(prevState => ({
      ...prevState,
      content: '',  // 清空输入框
    }));
  }, [requestChat]);

  const handlePromptsItemClick = useCallback((info) => {
    onSubmit(info.data.description);
    setState(prevState => ({
      ...prevState,
      historyMessages: [], // 清空历史消息
      content: '', // 清空输入框
    }));
  }, [onSubmit]);

  const onAddConversation = useCallback(() => {
    if (messages.length !== 0) {
      setState(prevState => ({
        ...prevState,
        messages: [], // 清空当前消息
        historyMessages: [], // 清空当前历史消息
        conversationId: null, // 清空当前会话ID
        activeKey: null, // 清空当前激活会话ID
      }));
    } else {
      message.info("已是最新会话");
    }
  }, [messages]);

  const onConversationClick = useCallback((key) => {
    setState(prevState => ({
      ...prevState,
      activeKey: key,
      conversationId: key,
      historyMessages: [], // 清空历史消息
    }));
  }, []);

  return (
    <Layout className={styles.layout}>
      <Sider className={styles.menu}
        theme="light"
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
        trigger={null} // 隐藏默认触发器
        width={xs ? 50 : 250} // 根据屏幕尺寸调整宽度
        collapsedWidth={xs ? 0 : 5}
        style={{
          overflow: 'auto',
          height: '100vh',
          position: 'fixed',
          left: 0,
        }}
      >
        <ConversationsManger
          onAddConversation={onAddConversation}
          onConversationClick={onConversationClick}
          conversationsItems={conversationsItems}
          activeKey={activeKey}
          collapsed={collapsed} // 可以根据折叠状态调整内部样式
        />
      </Sider>
      <Layout style={{ marginLeft: collapsed ? (xs ? 0 : 5) : (xs ? 0 : 250), transition: 'margin 0.2s' }}>
        <Header 
          style={{ 
            padding: 0,
            background: colorBgContainer,
            position: 'sticky',
            top: 0,
            zIndex: 1,
          }}
        >
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
          />
        </Header>
        <div className={styles.chat}>
          <BubbleChat
            items={messagesItems}
            placeholderNode={placeholderNode}
            RenderMarkdown={RenderMarkdown}
          />
          <AttachmentInput
            styles={styles}
            onSubmit={onSubmit}
            content={content}
            setContent={setContent}
            loading={loading}
            setLoading={setLoading}
            onCancel={onCancel}
          />
        </div>
      </Layout>
    </Layout>
  );
};
